package cn.midas.basic.service.impl;

import cn.midas.basic.constant.BaseConstants;
import cn.midas.basic.dto.LoginDto;
import cn.midas.basic.dto.WeChatDto;
import cn.midas.basic.exception.BusinessException;
import cn.midas.basic.service.ILoginService;
import cn.midas.basic.utils.AjaxResult;
import cn.midas.basic.utils.HttpUtil;
import cn.midas.basic.utils.MD5Utils;
import cn.midas.basic.utils.StrUtils;
import cn.midas.org.domain.Employee;
import cn.midas.org.mapper.EmployeeMapper;
import cn.midas.user.domain.Logininfo;
import cn.midas.user.domain.User;
import cn.midas.user.domain.Wxuser;
import cn.midas.user.mapper.LogininfoMapper;
import cn.midas.user.mapper.UserMapper;
import cn.midas.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    public Long id;
   /**
   * @Title: account
   * @Description: 用户登录业务层
   * @Author: Mr.She
   * @Version: 1.0
   * @Date:  2022/7/10 13:12
   * @Parameters: [loginDto]
   * @Return java.util.HashMap<java.lang.String,java.lang.Object>
   */
    @Override
    public HashMap<String, Object> account(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        // 1.参数为空校验
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)
                || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数为空，请重新填写！");
        }
        // 2.根据账号 type查询用户三个字段 username phone Email and type
        Logininfo  logininfo = logininfoMapper.loadByUsernameAndType(username, type);



        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null) {
            throw new BusinessException("账号密码错误，请重新填写！");
        }
        id = logininfo.getId();
        // 4.判断密码是否一致，加盐加密比较
        String passwordTmp = MD5Utils.encrypByMd5( password +logininfo.getSalt());
        if (!logininfo.getPassword().equals(passwordTmp)) {
            throw new BusinessException("账号密码错误，请重新填写！");
        }
        // 5.生成uuid作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid 和 logininfo设置到redis中设置30分钟有效
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 7.把logininfo中敏感信息设为空作为value
        logininfo.setPassword("");
        logininfo.setSalt("");
        // 8.将uuid和logininfo存入map中返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;


    }
    /**
    * @Title: weChat
    * @Description: 微信登录第二部
    * @Author: Mr.She
    * @Version: 1.0
    * @Date:  2022/7/10 17:18
    * @Parameters: [weChatDto]
    * @Return cn.midas.basic.utils.AjaxResult
    */
    @Override
    public AjaxResult weChat(WeChatDto weChatDto) {
        String code = weChatDto.getCode();
        // 1.判断参数是否为空
        if (StringUtils.isEmpty(weChatDto.getCode())){
            throw new BusinessException("参数为空！");
        }
        // 2.拼接二步曲请求地址，获取access_token、openid
        String tokenURL = BaseConstants.WeChatConstants.TOKEN_URL
                .replace("APPID",BaseConstants.WeChatConstants.APPIO)
                .replace("SECRET",BaseConstants.WeChatConstants.SECRET)
                .replace("CODE",code);
        // 3.发起请求获取到JSON字符串
        String jsonObjStr = HttpUtil.httpGet(tokenURL);
        // 4.将字符串JSON转换为JSON对象，获取到access_token&openid
        JSONObject jsonObject = JSONObject.parseObject(jsonObjStr);
        Object accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        // 5.根据openId查询t_wxuser
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        // 6.判断微信用户信息是否存在
        if (wxuser != null && wxuser.getUserId() != null){
            // 6.1.wx用户存在并且已经绑定了账号，直接免密登录
            // - 根据wxuser中的userid查询logininfo信息
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 生成UUID作为token存入到redis中设置有效期30分钟
            // 6.2.生成uuid作为key
            String token = UUID.randomUUID().toString();
            // 6.3.将uuid 和 logininfo设置到redis中设置30分钟有效
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            // 6.4.把logininfo中敏感信息设为空作为value
            logininfo.setPassword("");
            logininfo.setSalt("");
            // 8.将uuid和logininfo存入map中返回给前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);

        }
        // 6.2.不存在告诉前端用户跳转到账号绑定页面，传递参数到前端，因为我们在下个接口需要使用
        StringBuffer stringBuffer = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=").append(openId);
            return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(stringBuffer);



    }

    /**
     * @Title: binder
     * @Description: 微信登录绑定账号
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/10 15:49
     * @Parameters: [wxDto]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    @Transactional
    public HashMap<String, Object> binder(WeChatDto weChatDto) {
        String accessToken = weChatDto.getAccessToken();
        String openId = weChatDto.getOpenId();
        String phone = weChatDto.getPhone();
        String verifyCode = weChatDto.getVerifyCode();

        // 1.非空校验
        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId) ||StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(verifyCode) ){
            throw new BusinessException("参数异常！");
        }

        // 2.手机验证码校验
        String phoneCodeKey = BaseConstants.GraphCodeConstants.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 3.判断存不存在
        if (phoneCodeValueRedis == null){
            throw new BusinessException("验证码已经过期，请重新填写！");
        }
        //4判断手机验证码是否一致
        //4.1获取redis中验证码
        String[] split = phoneCodeValueRedis.toString().split(":");
        String phoneCode = split[0];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码不正确，请重新填写！");
        }

        // 3.根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if (user == null){// 3.1.不存在：初始化user&logininfo并保存

            user = weChatDto2User(phone);
            userMapper.save(user);
            //3.4 将user的数据拷贝到logininfo表中
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            // 将表logininfo主键id设置到user表
            user.setLogininfoId(logininfo.getId());
            userMapper.update(user);
        }else {// 3.2.存在：查询Logininfo
           logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 4.根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserURL = BaseConstants.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        String wxUserStr = HttpUtil.httpGet(wxUserURL);
        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 5.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 6.返回成功登录map
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;




    }


    private User weChatDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
